package servlet;

import dao.UserDao;
import users.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String key = request.getParameter("key");
        //HttpSession session = request.getSession();
        //User u = null;
        //u = UserDao.login(username,password);
        User u = UserDao.login(username,password);
        if (u!=null){
            request.getSession().setAttribute("user",u);
            request.setAttribute("username", username);
            System.out.println("1");
            //response.sendRedirect("LoginSuccess.jsp");
            request.getRequestDispatcher("/LoginSuccess.jsp").forward(request, response);
            //判断参数是否为空，如果不为空，则为退出操作
            if (key!=null&&"logout".equals(key)) {
                //销毁session对象
                request.getSession().invalidate();
            }
        }
        else{
            request.setAttribute("username", username);
            request.setAttribute("error", "用户名或密码错误，请重新输入！");
            request.getRequestDispatcher("/Login.jsp").forward(request,response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
